﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenComposite.EII.Forms;
using OpenComposite.EII.Repository;
using OpenComposite.Base.Collections;

namespace OpenComposite.EII.RepositoryUIs
{
	public partial class FormCreateNewKPI : FormCreateNewBase
	{
		public FormCreateNewKPI(KeyPerformanceIndicator item, bool bAllowToContinue) :
			base(item, item, bAllowToContinue)
		{
			InitializeComponent();
			init();
		}

		private KpiUnit baseUnit = null;
		
		private void init()
		{
			base.CreateAtToolStrip.Visible = false;
			DataTable dt = Global.Data.GetDataTypes();
			cmbDataType.BeginUpdate();
			try {
				cmbDataType.Items.Clear();
				foreach ( DataRow row in dt.Rows ) {
					cmbDataType.Items.Add(row["datatype"].ToString());
				}
				cmbDataType.SelectedItem = "float";
			} finally {
				cmbDataType.EndUpdate();
			}
			dgvUnits.AutoGenerateColumns = false;
			dgvUnits.DataSource = KPI.ExtendedProperties.Units;
			baseUnit = KPI.BaseUnit;
			txtName.Text = KPI.Name;
			txtCalcType.Text = KPI.CalculationType;
			txtDescription.Text = KPI.Description;
			cmbDataType.SelectedItem = KPI.DataType;
		}

		private KeyPerformanceIndicator KPI
		{
			get { return base.RepositoryItem as KeyPerformanceIndicator; }
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
		}

		protected override void OnSaveClose(CancelEventArgs e)
		{
			if ( save() ) {
				base.OnSaveClose(e);
			}
		}

		protected override void OnSaveContinue(CancelEventArgs e)
		{
			if ( save() ) {
				base.OnSaveContinue(e);
			}
		}

		protected override void OnCancel()
		{
			// don't call base.OnCancel, because this form is used for editing too!
			this.DialogResult = DialogResult.Cancel;
			if ( !IsFormClosing )
				this.Close();
		}

		/// <summary>
		/// Saves this instance.
		/// </summary>
		/// <returns></returns>
		private bool save()
		{
			bool hasBasUnit = false;
			foreach ( KpiUnit unit in KPI.ExtendedProperties.Units ) {
				if ( unit.IsBaseUnit ) {
					hasBasUnit = true;
					break;
				}
			}
			if ( !hasBasUnit ) {
				MessageBox.Show("Please specify at least one unit as base unit!", 
					"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}
			if ( baseUnit != KPI.BaseUnit && baseUnit != null ) {
				if ( MessageBox.Show("The base unit of this KPI has changed. You must adjust all metrics of this KPI to the new value. Do you want to conitinue?",
						"Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No ) {
					return false;
				}
			}
			KPI.Name = txtName.Text;
			KPI.CalculationType = txtCalcType.Text;
			KPI.Description = txtDescription.Text;
			KPI.DataType = (string)cmbDataType.SelectedItem;
			KPI.Save();
			//KPI.NullValue = "0.0";
			return true;

		}

		private void txtName_KeyPress(object sender, KeyPressEventArgs e)
		{
			// valid for KPIs
			//e.Handled = !Helpers.IsValidCharForName(e.KeyChar);
		}

		private void btnAddUnit_Click(object sender, EventArgs e)
		{
			if ( string.IsNullOrEmpty(txtUnitName.Text) ) return;
			KpiUnit unit = new KpiUnit(txtUnitName.Text);
			KPI.ExtendedProperties.Units.Add(unit);
			txtUnitName.Text = "";
			txtUnitName.Focus();
			txtUnitName.SelectAll();
		}

		private void dgvUnits_KeyUp(object sender, KeyEventArgs e)
		{
			if ( dgvUnits.SelectedCells.Count == 0 ) return;
			if ( e.KeyCode == Keys.Delete ) {
				deleteSelectedUnit();
			}
		}

		private void btnRemove_Click(object sender, EventArgs e)
		{
			if ( dgvUnits.SelectedCells.Count == 0 ) return;
			deleteSelectedUnit();
		}

		private void deleteSelectedUnit()
		{
			KpiUnit unit = dgvUnits.Rows[dgvUnits.SelectedCells[0].RowIndex].DataBoundItem as KpiUnit;
			if ( MessageBox.Show(string.Format("This will delete the selected Unit '{0}'. Do you want to contine?", unit.Name),
				"Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No ) {
				return;
			}
			if ( unit != null ) {
				KPI.ExtendedProperties.Units.Remove(unit);
			}
		}

		private void dgvUnits_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
		{
		}

		private void dgvUnits_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
			if ( e.RowIndex < 0 ) return;
			if ( e.ColumnIndex == colBaseUnit.Index ) {
				KpiUnit changed = dgvUnits.Rows[e.RowIndex].DataBoundItem as KpiUnit;
				if ( !changed.IsBaseUnit ) {
					BindingListEx<KpiUnit> units = KPI.ExtendedProperties.Units;
					foreach ( KpiUnit unit in units ) {
						if ( unit == changed ) continue;
						unit.IsBaseUnit = false;
					}
				}
				dgvUnits.CommitEdit(DataGridViewDataErrorContexts.Commit);
				dgvUnits.Refresh();
			}
		}

		private void dgvUnits_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			if ( e.RowIndex < 0 ) return;
			if ( e.ColumnIndex == colValue.Index ) {
			}
		}

		private void dgvUnits_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
		{
			if ( e.RowIndex < 0 || e.Value == null ) return;
			if ( e.ColumnIndex == colValue.Index ) {
				decimal value;
				decimal.TryParse(e.Value.ToString().Replace(',', '.'),
					System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture,
					out value);
				e.Value = value;
				e.ParsingApplied = true;
			}
		}

	}
}
